from cold_start_analyzer.base_analyzer import BaseAnalyzer
from cold_start_analyzer.consts import NOT_AVAILABLE
from cold_start_analyzer import db_helper


class Phase1SceneSession(BaseAnalyzer):
    description = "桌面处理: 从SceneSession接受Touch事件到发起QueryAbilityInfo"
    def get_result(self):
        """
        起点： touch_test
        终点： query_ability_info
        """
        if 'Phase1All' not in self.context:
            return NOT_AVAILABLE
        start_ts = self.context['Phase1All']['touch_test']
        end_ts = self.context['Phase1All']['end_ts']
        patterns = [
            'H:%QueryAbilityInfo%',
            'H:%QueryAbilityInfos%',
        ]
        event = db_helper.get_first_event_after(
            self.cursor,
            patterns,
            start_ts=start_ts,
            end_ts=end_ts,
        )
        if not event:
            # 记录一个保底时间，避免后续阶段崩溃
            self.context['Phase1All']['query_ability_info'] = start_ts
            return NOT_AVAILABLE
        self.context['Phase1All']['query_ability_info'] = event[0]
        return event[0] - start_ts
